package com.easytouch.vm.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Pair;

import com.easytouch.core.DriverThread;
import com.easytouch.core.utils.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by gulin on 2017/9/15.
 */

public class AliDemoService extends Service {
    private static final String ALI_URL = "http://139.224.224.48:3000/get_goods"; //"http://114.215.71.10:3000/get_goods";
    private static Log mLogger; //日志
    AliDemoThread mAliDemoThread;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (mAliDemoThread != null) {
            return super.onStartCommand(intent, flags, startId);
        }
        mLogger = new Log("AliDemoService.txt");
        mAliDemoThread = new AliDemoThread();
        mAliDemoThread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    public class AliDemoThread extends Thread {

        @Override
        public void run() {
            super.run();

            while (true)
            {
                SystemClock.sleep(3000);

                URL realurl = null;
                InputStream in = null;
                HttpURLConnection conn = null;
                StringBuffer sBuffer = null;
                try {
                    realurl = new URL(ALI_URL);
                    conn = (HttpURLConnection) realurl.openConnection();
                    conn.setDoInput(true);
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(15000);
                    conn.setRequestMethod("GET");
                    if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                        sBuffer = new StringBuffer();
                        byte[] buf = new byte[1024];
                        in = conn.getInputStream();
                        for (int n; (n = in.read(buf)) != -1;) {
                            sBuffer.append(new String(buf, 0, n, "UTF-8"));
                        }
                        handleResult(sBuffer.toString());
                    }else{
                        mLogger.e("http error");
                    }

                } catch (MalformedURLException e) {
                    mLogger.e(e.toString());
                } catch (ProtocolException e) {
                    mLogger.e(e.toString());
                } catch (UnsupportedEncodingException e) {
                    mLogger.e(e.toString());
                } catch(SocketTimeoutException e){
                    mLogger.e(e.toString());
                }catch (UnknownHostException e) {
                    mLogger.e(e.toString());
                }catch (IOException e) {
                    mLogger.e(e.toString());
                }
                finally{
                    try {
                        if(in != null) in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(conn != null) conn.disconnect();
                }
            }
        }

        private void handleResult(final String message)
        {
            JSONObject object;
            mLogger.i(message);
            try
            {
                object = new JSONObject(message);
                String status = object.getString("status");
                if(status.equals("normal"))
                {
                    return;
                }
                else if(status.equals("buying"))
                {
                    String location = object.getString("location");
                    int column = 1;
                    try
                    {
                        column = Integer.parseInt(location);
                    }
                    catch (NumberFormatException e)
                    {
                        mLogger.e("NumberFormatException:" + e.toString());
                        return;
                    }
                    outGoods(9, column);
                }
            }
            catch (JSONException e)
            {
                mLogger.e("alipay json error");
            }
        }

        private void outGoods(final int box, final int column)
        {
            SimpleDateFormat sd = new SimpleDateFormat("HHmmss", Locale.US);
            String tradeTrace = sd.format(new Date());

            boolean result = DriverThread.getInstance().outGoods(box, column, 100, DriverThread.OUT_GOODS_ALIPAY, tradeTrace, tradeTrace);
            if(!result)
            {
                mLogger.e("outGoods result failed");
                return;
            }
            int step = 0;
            int r = -1;
            try {
                while (step <= 120) {
                    Thread.sleep(500);
                    step++;
                    Pair<Integer, Integer> pair = DriverThread.getInstance().getResult(tradeTrace);
                    if(pair != null)
                    {
                        r = pair.first;
                        break;
                    }
                }
            } catch (InterruptedException e) {
            }
            mLogger.i("outGoods result:" + String.valueOf(r));
        }
    }
}
